import { BrowserWindow, ipcMain } from 'electron';
import { helloController } from '../controller/hello/hello.controller';
import logger from "../tools/log/log"
/**
 * 调度路由
 * code:{
 *   200 正常返回
 *   404 找不到
 *   500 错误
 *   
 * }
 */
export class electronRouter {
    HelloController: helloController
    constructor(win: BrowserWindow) {
        this.HelloController = new helloController(win)
        this.watchFromRender(win);
    }

    watchFromRender(win) {

        //普通通信 监听 on消息------------------------------
        ipcMain.on('electronRenderToMain', (event, data) => {
            //logger.info('electronRenderToMain:' + JSON.stringify(data))
            //on 路由
            switch (data.url) {
                case 'hello':
                    //console.log('electronRenderToMain-hello.controller', data);
                    if (this.HelloController[data.action]) {
                        this.HelloController[data.action](event, data)
                    } else {
                        console.log('send the function is not found!');
                    }
                    break;
                default:
                    console.log('send the controller is not found!');
            }
        })

        //ajax通信 监听 handle消息---------------------------
        ipcMain.handle('electronAjax', async (event, data) => {
            //logger.info('electronAjax:' + JSON.stringify(data))
            let response = {
                code: 200,
                data: null,
                msg: ''
            };
            //handle 路由
            switch (data.url) {
                case 'hello':
                    if (this.HelloController[data.action]) {
                        response.data = await this.HelloController[data.action](event, data)
                    } else {
                        response.code = 404;
                        response.msg = 'ajax the function is not found!'
                    }
                    break;
                default:
                    response.code = 404;
                    response.msg = 'ajax the controller is not found!';
            }
            return response;
        })
    }
}